import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.calendar.CalendarEntry;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarFeed;
import com.google.gdata.data.extensions.When;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;

public class CalendarTest {

	public static void main(String[] args) {
		CalendarService myService = new CalendarService(
				"exampleCo-exampleApp-1.0");
		try {
			myService.setUserCredentials("huatingzl@gmail.com",
					"huating8232828");
		} catch (AuthenticationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		URL feedUrl;
		try {
			feedUrl = new URL(
					"http://www.google.com/calendar/feeds/default/allcalendars/full");
			CalendarFeed resultFeed = myService.getFeed(feedUrl,
					CalendarFeed.class);
			for (int i = 0; i < resultFeed.getEntries().size(); i++) {
				CalendarEntry entry = resultFeed.getEntries().get(i);
				System.out.println("\t" + entry.getTitle().getPlainText());
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		System.out.println("Your calendars:");
		System.out.println();
		
		
		
		URL postURL = null;
		try { 
			postURL = new URL(
					"http://www.google.com/calendar/feeds/huatingzl@gmail.com/private/full");
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		CalendarEventEntry myEvent = new CalendarEventEntry();

		// Set the title and description
		myEvent.setTitle(new PlainTextConstruct("Pi Day Party"));
		myEvent.setContent(new PlainTextConstruct(
				"I am throwing a Pi Day Party!"));
		myEvent.setCanEdit(false);

		// Create DateTime events and create a When object to hold them, then
		// add
		// the When event to the event
		DateTime startTime = DateTime
				.parseDateTime("2010-07-06T15:00:00-09:00");
		DateTime endTime = DateTime.parseDateTime("2010-07-06T15:00:00-09:00");
		When eventTimes = new When();
		eventTimes.setStartTime(startTime);
		eventTimes.setEndTime(endTime);
		myEvent.addTime(eventTimes);

		// POST the request and receive the response:
		try {
			CalendarEventEntry insertedEntry = myService.insert(postURL, myEvent);
		} catch (IOException e) { 
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ServiceException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}